package com.demo.employees.web.servlet;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.demo.employees.model.Employee;
import com.demo.employees.service.EmployeeService;
import com.demo.employees.util.SimpleFactory;

/**
 * Servlet implementation class AddEmployee
 */
public class AddEmployeeServlet extends HttpServlet {
	private EmployeeService employeeService = SimpleFactory.getEmployeeService();
	
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddEmployeeServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher("addEmployee.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//入参接收
		String nameStr = request.getParameter("name");
		String ageStr = request.getParameter("age");
		String salaryStr = request.getParameter("salary");
		String hireDateStr = request.getParameter("hireDate");
		try {
			//类型转化
			int age = Integer.parseInt(ageStr);
			BigDecimal salary = new BigDecimal(salaryStr);
			Date hireDate = new SimpleDateFormat("yyyy-MM-dd").parse(hireDateStr);
			
			Employee employee = new Employee();
			employee.setName(nameStr);
			employee.setAge(age);
			employee.setSalary(salary);
			employee.setHireDate(hireDate);
			
			employeeService.saveEmployee(employee);
			response.sendRedirect(request.getContextPath()+"/ListEmployee");
		} catch (NumberFormatException e) {
			request.setAttribute("errMsg", "入参有误");
			request.getRequestDispatcher("error.jsp").forward(request, response);
		} catch (Exception e) {
			request.setAttribute("errMsg", "未知错误");
			request.getRequestDispatcher("error.jsp").forward(request, response);
		}
			
	}

}
